/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.home.fragment.home;

import static com.dataoke.shoppingguide.app773026.bean.Constants.DA_TAO_KE_GOODS_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.INDEX_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_LIST_URL;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.base.fragments.BaseFragment;
import com.dataoke.shoppingguide.app773026.bean.dataoke.DataokeGoodsListResBean;
import com.dataoke.shoppingguide.app773026.bean.haodanku.HaodankuIndexDataBean;
import com.dataoke.shoppingguide.app773026.bean.haodanku.HaodankuIndexResBean;
import com.dataoke.shoppingguide.app773026.util.HttpTools;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class HomeContentFragment extends BaseFragment implements
        OnRefreshLoadMoreListener {

    private RecyclerView mRecycler;

    protected SmartRefreshLayout mRefreshLayout;

    private HomeContentAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_tab;
    }
    public static HomeContentFragment newInstance() {
        HomeContentFragment homeDataokeFragment = new HomeContentFragment();
        return homeDataokeFragment;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mRecycler = root.findViewById(R.id.recycler);
        mRefreshLayout = root.findViewById(R.id.refreshLayout);
        mRefreshLayout.setEnableFooterFollowWhenNoMoreData(true);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
    }

    @Override
    protected void initData() {

        HttpTools.get(INDEX_URL, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("HaodankuListFragment", INDEX_URL + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                HaodankuIndexResBean indexResBean = JSON.parseObject(response.body().string(), HaodankuIndexResBean.class);
                if(indexResBean.getCode() == 200) {
                    getActivity().runOnUiThread(() -> {
                        processData(indexResBean.getData());
                    });
                    //预加载列表数据
                    HttpTools.get(String.format(DA_TAO_KE_GOODS_LIST_URL, 1, "9.9"), new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Log.e("HaodankuListFragment", String.format(PRODUCT_LIST_URL, 1) + e.getMessage());
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            DataokeGoodsListResBean productListBean = JSON.parseObject(response.body().string(), DataokeGoodsListResBean.class);
                            if(productListBean.getCode() == 0 && adapter != null) {
                                adapter.setGoodsList(productListBean.getData().getList());
                            }
                        }
                    });
                }
            }
        });

    }
    /**
     * 解析数据
     */
    private void processData(HaodankuIndexDataBean dataBean) {
        //使用FastJson去解析数据，将Json字符串转换成一个ResultBeanData对象

        //有数据就设置适配器
        adapter = new HomeContentAdapter(this, dataBean);
        mRecycler.setAdapter(adapter);

        GridLayoutManager manager = new GridLayoutManager(mContext,1);
        //设置跨度大小监听
//        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                if (position <= 3){
//                    //隐藏
////                        ib_top.setVisibility(View.GONE);
//                    mRecycler.requestDisallowInterceptTouchEvent(false);
//                }else {
//                    //显示
////                        ib_top.setVisibility(View.VISIBLE);
//                    mRecycler.requestDisallowInterceptTouchEvent(true);
//                }
//                //只能返回1
//                return 1;
//            }
//        });
        //设置布局管理者
        mRecycler.setLayoutManager(manager);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if(adapter.listViewHolder != null) {
            adapter.listViewHolder.onLoadMore(refreshLayout);
        }else {
            refreshLayout.finishLoadMore(0, true, false);
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if(adapter.listViewHolder != null) {
            adapter.listViewHolder.onRefresh(refreshLayout);
        } else {
            refreshLayout.getLayout().postDelayed(() -> {
                refreshLayout.finishRefresh();
                refreshLayout.resetNoMoreData();
            }, 1500);
        }

    }
}
